#!/bin/bash
LOG_DIR="/www/wwwlogs"
ACTION=$1

case $ACTION in
    "read")
        # 获取所有日志文件
        for logfile in $LOG_DIR/*.log; do
            if [ -f "$logfile" ]; then
                filename=$(basename "$logfile")
                site=${filename%.log}
                
                echo "=== $site ==="
                # 总请求数
                echo "Requests: $(wc -l < "$logfile")"
                
                # 状态码统计
                echo "Status Codes:"
                awk '{print $9}' "$logfile" | sort | uniq -c | sort -rn
                
                # Top 10 IPs with UA
                echo "Top IPs:"
                awk '{ip=$1; ua=""; for(i=12;i<=NF;i++) ua=ua" "$i; print ip "\t" ua}' "$logfile" | sort | uniq -c | sort -rn | head -n 10
                
                # 总流量
                echo "Traffic:"
                awk '{sum+=$10} END {print sum}' "$logfile"
                
                # 最后访问时间
                echo "Last Access:"
                tail -n 1 "$logfile" | awk '{print $4}'
                
                # 每个 IP 访问最多的 3 个页面
                echo "Top Pages per IP:"
                awk '{print $1, $7}' "$logfile" | sort | uniq -c | sort -rn | head -n 30
                
                # 最新的10条日志记录
                echo "Latest Logs:"
                tail -n 10 "$logfile"
                
                echo "=== END $site ==="
            fi
        done
        ;;
    *)
        echo "Unknown action: $ACTION"
        exit 1
        ;;
esac